package com.shijie.utlis;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class RedisIdWorker {

    private final StringRedisTemplate stringRedisTemplate;

    private static final long BEGIN_TIMESTAMP_SECOND;

    private static final short COUNT_BITS; // 序列号位数

    static {
        BEGIN_TIMESTAMP_SECOND = 1735718400L; // 2025-01-01T08:00
        COUNT_BITS = 32;
    }

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public long nextId(String keyPrefix) {
        // 对于题库数据量不大且并发低(管理员操作)，不使用类雪花算法。
        if ("pool-id".equals(keyPrefix)) {
            Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":all");
            return count == null ? 1L : count;
        }

        // 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowTimestampSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowTimestampSecond - BEGIN_TIMESTAMP_SECOND;

        // 使用redis生成序列号
        //获取当前日期到天
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        // 自增长序列号
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);

        // 位运算拼接生成全局ID 时间戳+序列号
        return timestamp << COUNT_BITS | (count == null ? 1L : count);
    }

}
